package com.girant.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.girant.DTO.SearchResultDTO;
import com.girant.entity.Material;
import com.girant.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/material")
@CrossOrigin(origins = "*")
public class MaterialController {
    @Autowired
    private MaterialService materialService;
    // 将前端JSON序列化的锚点字符串解析为Object[]
    @GetMapping("/search")
    public SearchResultDTO<Material> search(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String searchAfter // 接收JSON字符串，Java 代码中会默认取值为 null
    ) throws IOException {
        Object[] searchAfterObj = null;//首页
        if (searchAfter != null && !searchAfter.isEmpty()) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                searchAfterObj = mapper.readValue(searchAfter, Object[].class);
            } catch (Exception e) {
                log.error("searchAfter格式错误: {}", searchAfter, e);
                searchAfterObj = null;
            }
        }
        return materialService.search(keyword, size, searchAfterObj);
    }
}
